#include "trap.h"
   .set noat                # 禁止使用保留寄存器$at
   .set noreorder           # 禁止指令重排序
   .globl main
   .text

main:
   # 加载高位地址部分到$s2和$s3
   lui  $s2, 0x7FFF
   lui  $s3, 0x7FFF

   # 执行加法并引发溢出异常
   add  $s1, $s2, $s3       # Overflow exception

   # 增加$s0值以触发系统调用
   addi $s0, $s0, 0x1001
   syscall                  # System call

   # 调整$s0值以触发断点异常
   addi $s0, $s0, 0x1003
   break                    # Breakpoint exception

   # 加载地址并触发地址加载错误异常
   lui  $s0, 0x1000
   addi $s0, $s0, 0x1000
   lw   $t1, 0x5($zero)     # Address load error

   # 调整$s0值以触发地址存储错误异常
   addi $s0, $s0, 0x1002
   sw   $t0, 0x9($zero)     # Address store error

   # 简单调整寄存器值，防止遗漏步骤
   addi $s0, $s0, 0x00FF

   # 跳转到成功标志
   j success
   nop

   # 异常处理表
   .org 0x380
      mfc0 $a1, $13            # 从CP0寄存器中读取异常原因
      ori  $a2, $zero, 0x10    # Address load error code
      beq  $a1, $a2, exc_eret
      nop
      mfc0 $a1, $13
      ori  $a2, $zero, 0x14    # Address store error code
      beq  $a1, $a2, exc_eret  
      nop
      mfc0 $a1, $13
      ori  $a2, $zero, 0x20    # System call code
      beq  $a1, $a2, exc_eret 
      nop
      mfc0 $a1, $13
      ori  $a2, $zero, 0x24    # Breakpoint code
      beq  $a1, $a2, exc_eret 
      nop
      mfc0 $a1, $13
      ori  $a2, $zero, 0x28    # Reserved instruction code
      beq  $a1, $a2, exc_eret 
      nop 
      mfc0 $a1, $13
      ori  $a2, $zero, 0x30    # Overflow exception code
      beq  $a1, $a2, exc_eret 
      nop

      # 跳转到错误处理
      j error
      nop

      # 错误处理逻辑
      error:
      lui  $a3, 0xFFFF
      ori  $a3, $a3, 0xFFFF
      j loop
      nop

      # 成功标志逻辑
      success:
      lui  $a3, 0x6666
      ori  $a3, $a3, 0x6666
      j End
      nop
      
      # 无限循环
      loop:
      j loop
      nop

      # 异常返回处理
      .org 0x600
      exc_eret:
      addiu $a3, $a3, 0x1    # 更新异常计数器
      mfc0  $t1, $14         # 读取异常程序计数器
      ori   $t0, $zero, 0x4  # 调整偏移
      add   $t1, $t1, $t0
      mtc0  $t1, $14         # 更新程序计数器
      nop

      .set mips32
      eret                   # 返回异常
      .set mips1
      nop
      nop
      nop

      # 程序结束
      End:
      HIT_GOOD_TRAP          # 结束模拟器